from PyQt4 import QtGui, QtCore
from three_trackballs import tw

tw.globalInit()
tw.startListening()

app = QtGui.QApplication([])

class exampleWidget(QtGui.QWidget):
    
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.resize(750, 200)
        self.setMouseTracking(True)
        
        self.dx = [0]*3
        self.dy = [0]*3
        self.dw = [0]*3
        
    def xx(self, idx):
        return self.dx[idx]/10

    def yy(self, idx):
        return self.dy[idx]/10
        
    def ww(self, idx):
        return self.dw[idx]
        
    def paintEvent(self, event):
        QtGui.QWidget.paintEvent(self, event)
        
        p = QtGui.QPainter()
        p.begin(self)

        p.setPen(QtGui.QColor(0, 0, 0))
                
        p.drawRect(QtCore.QRect(  1, 1, 200, 200))
        p.drawRect(QtCore.QRect(200, 1, 50, 200))
        p.drawRect(QtCore.QRect(250, 1, 200, 200))
        p.drawRect(QtCore.QRect(450, 1, 50, 200))
        p.drawRect(QtCore.QRect(500, 1, 200, 200))
        p.drawRect(QtCore.QRect(700, 1, 50, 200))

        # movable ones!

        sz = 10

        p.drawRect(QtCore.QRect(100+self.xx(0)-sz/2, 100+self.yy(0)-sz/2, sz, sz))
        p.drawRect(QtCore.QRect(350+self.xx(1)-sz/2, 100+self.yy(1)-sz/2, sz, sz))
        p.drawRect(QtCore.QRect(600+self.xx(2)-sz/2, 100+self.yy(2)-sz/2, sz, sz))

        sz2 = 1

        p.drawRect(QtCore.QRect(200, 100+self.ww(0)-sz2, 50, sz2))
        p.drawRect(QtCore.QRect(450, 100+self.ww(1)-sz2, 50, sz2))
        p.drawRect(QtCore.QRect(700, 100+self.ww(2)-sz2, 50, sz2))
        
        p.end()            
        
    def wheelEvent(self, event):    
        QtGui.QWidget.wheelEvent(self, event)
        index = tw.getTrackballWheelIndex()
        if index != -1:
            self.dw[index] = tw.getTrackballWheel(index)
            self.update()
        
    def mouseMoveEvent(self, event):
        QtGui.QWidget.mouseMoveEvent(self, event)
        index = tw.getTrackballCursorIndex()
        if index != -1:
            self.dx[index] = tw.getTrackballDx(index)
            self.dy[index] = tw.getTrackballDy(index)
            self.update()

w = exampleWidget()
w.show()
w.raise_()
app.exec_()

tw.stopListening()
tw.globalDone()